<template>
  <div class="index">
    <div class="head">
      <div class="title">
        博客管理系统
      </div>
        <div class="left">
          <div class="userPicArea">
            <div class="header" :style="{backgroundImage:'url('+userPic+')'}">
            </div>
          </div>
          <el-dropdown class="dropdown"  @command="handleCommand">
            <span class="el-dropdown-link">
              {{userNickname}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">更改密码</el-dropdown-item>
              <el-dropdown-item command="b">更改信息</el-dropdown-item>
              <el-dropdown-item command="c">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
    </div>
    <div class="body">
      <div class="left">
        <template v-for="item in routerList">
          <router-link 
          :key="item.name"  
          tag="div" 
          class="route" 
          :class="{active:($route.path).toLowerCase()==(item.path).toLowerCase()}"
           :to="item.path">
           {{ item.title }}
          </router-link>
        </template>
      </div>
      <div class="right">
        <router-view/>
      </div>
    </div>
    <!-- 更改密码的弹出框 -->
    <el-dialog
      title="更改密码"
      :visible.sync="changePwddialogVisible"
      width="30%">
      <label>请输入原密码</label><el-input v-model="oldPwd"></el-input>
      <label>请输入新密码</label><el-input v-model="newPwd"></el-input>
      <label>请输入再次输入新密码</label><el-input v-model="renewPwd"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changePwddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRePwd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 更改密码的弹出框 -->
    <!-- 更改信息的弹出框 -->
    <CutHeadImg></CutHeadImg>
    <el-dialog title="更改信息"
    :visible.sync="changeUserPicVisible"
    >
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="prePostUserPic" :src="prePostUserPic" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
      <!-- action="https://jsonplaceholder.typicode.com/posts/" -->

    <!-- <div class="imgbox" ref="imgbox">
      <div class="seledArea" ref="seledArea"></div>
      <img @click="areaSelect" class="img" style=" " v-if="prePostUserPic" :src="prePostUserPic" alt="">
    </div>
    裁剪后：<img src="" alt=""> -->
    <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="sureUpdateAvatar" type="primary">点击上传</el-button>
        <el-button @click="changeUserPicVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 更改信息的弹出框 -->
  </div>
</template>
<script>
import {getUserInfo,updatepwd,updateAvatar} from "@/api/user"
import CutHeadImg from "@/components/index/CutHeadImg.vue"
import Cookies from 'js-cookie'
import { mapState } from 'vuex'
export default{
  components:{CutHeadImg},
  data(){
    return{
      userNickname:"",
      userPic:"",
      changePwddialogVisible:false,
      changeUserPicVisible:false,
      oldPwd:"",
      newPwd:"",
      renewPwd:"",
      prePostUserPic:"",
      postFile:"",
      selectArea:[],
      route:this.$route,
      intexRoute:[
        
      ],
      fileList: []
    }
  },
  methods:{
    getUserinfo(){
      getUserInfo().then(res=>{
        this.$store.commit("setUserId",res.data.id)
        this.userNickname = res.data.nickname;
        this.userPic ='http://localhost:3000/' + res.data.userPic;
      })
    },
    handleCommand(command){
      switch (command) {
        case "a":
          this.changePwddialogVisible = true;
          break;
        case "b":
          this.changeUserPicVisible = true;
        break;
        case "c":
          Cookies.remove("tooken");
          this.$router.push("/login")
        break;
        default:
          break;
      }
    },
    /**
     * 
     * 获取裁剪位置
     */
     areaSelect(e){
      var obj = {
        offsetX:e.offsetX,
        offsetY:e.offsetY
      }
      if (this.selectArea.length==0) {
        var arr = this.selectArea;
        arr.push(obj);
        this.selectArea = arr;
      }else if(this.selectArea.length==1){
        var arr = this.selectArea;
        arr.push(obj);
        this.selectArea = arr;
        var dom = this.$refs.seledArea;
        let width = Math.abs(arr[0].offsetX - arr[1].offsetX)
        let height = Math.abs(arr[0].offsetY - arr[1].offsetY);
        let Top = arr[0].offsetY>arr[1].offsetY?arr[1].offsetY:arr[0].offsetY
        let Left = arr[0].offsetX>arr[1].offsetX?arr[1].offsetX:arr[0].offsetX
        let fixed = width<height?width:height
        dom.style.width=fixed+"px";
        dom.style.height=fixed+"px";
        dom.style.border="1px solid #000";
        dom.style.top=Top+"px"
        dom.style.left=Left+"px"
      }
      else{
        var dom = this.$refs.seledArea;
        dom.style=null;
        this.selectArea =[]
      }
   
     },
    confirmRePwd(){
      var oldPwd = this.oldPwd;
      var newPwd = this.newPwd;
      var renewPwd = this.renewPwd;
      if (renewPwd!=newPwd) {
        this.$message.error("再次输入的密码和旧密码应该相同");
        return;
      }
      if (oldPwd == newPwd) {
        this.$message.error("新设的密码不应和旧密码相同");
        return;
      }
      var obj = {
        oldPwd,
        newPwd
      }
      updatepwd(obj).then(res=>{
        if (res.status==0) {
          Cookies.remove("tooken");
          this.$router.push("/login")
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleAvatarSuccess(res, file) {
      // console.log(file.raw);
      this.postFile = file.raw;
      this.prePostUserPic = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    /**
     * 确定更改用户头像
     */
    sureUpdateAvatar(){
      var avatar = this.postFile;
      console.log(this.postFile);
      if (!avatar) {
        this.$message.error("请先上传用户头像")
        return;
      }
      // 手工构造一个 form 对象
			var formData = new FormData();
			formData.append('files', avatar); // 'file' 为HTTP Post里的字段名, file 对浏览器里的File对象
      updateAvatar(formData).then(res=>{
        if (res.status==0) {
          this.getUserinfo();
          this.prePostUserPic = null;
          this.changeUserPicVisible = false;
        }
      })
    },
    AlertchangeuserPic(){
    },
    AlertchangePwd(){
      this.changePwddialogVisible = true;

    },
    layout(){

    },
    handleClosePwddialog(){

    },
    getBase(file){
      console.log(file);
      let blob= file;
      this.prePostUserPic = blob;
      // const a = new FileReader();
      // a.readAsDataURL(blob);
      // a.onload = (e) => {
      //   const base64 = e.target.result;
      // }
    }
  },
  created(){
    this.getUserinfo();
    console.log(this.routerList);
  },
  mounted(){
  },
  computed:{
    ...mapState(['routerList'])
  }
}
</script>
<style scoped lang="scss">
  .index{
    width: 100vw;
    height: 100vh;
    .head{
      width: 100%;
      line-height: 100px;
      font-size: 30px;
      padding-left: 20px;
      font-weight: 800;
      height: 100px;
      color: #fff;
      display: flex;
      background-color: #000000;
      align-items: center;
      justify-content: space-between;
      .left{
        width: 200px;
        height: 100px;
        display: flex;
        
        .userPicArea{
          height: 100px;
          width: 100px;
          display: flex;
          justify-content: center;
          align-items: center;
          .header{
            width: 50px;
            height: 50px;
            background-size: contain;
            background-position: center center;
            border-radius: 50%;
            background-repeat: no-repeat;
            // background: pink;
          }
        }
      }
    }
    .body{
      width: 100%;
      height: calc(100vh - 100px);
      display: flex;
      .left{
        width: 180px;
        background-color: #353535;
        height: 100%;
        .route{
          user-select: none;
          color: #ccc;
          height:80px;
          line-height:80px;
          text-align: center;
          cursor: pointer;
        }
        .active {
          border-bottom: 4px solid red;
        }
        .dropdown{
          cursor: pointer;
          .el-dropdown-link{
            cursor: pointer;
            line-height: 200px;
          }
        }
      }
      .right{
        height: calc(100vh - 100px);        
        flex: 1;
      }
    }
  }
  .imgbox{
    position: relative;
    .img{
      cursor:crosshair;
      height: 400px;
      outline: 1px solid red;
      // flex-grow: 1;
    }
    .seledArea{
      position: absolute;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
